// Definition for a binary tree node.
function TreeNode(val, left, right) {
  this.val = (val === undefined ? 0 : val)
  this.left = (left === undefined ? null : left)
  this.right = (right === undefined ? null : right)
}

function createTree(arr) {
  if (arr.length < 1)
    return null;
  let NodeArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == null) {
      NodeArr.push(null);
      continue;
    }
    let tempNode = new TreeNode(arr[i], null, null);
    NodeArr.push(tempNode);
  }
  for (let i = 0; i < arr.length; i++) {
    if (NodeArr[i] == null) continue;
    if (2 * i + 1 < arr.length)
      NodeArr[i].left = NodeArr[2 * i + 1];
    if (2 * i + 2 < arr.length)
      NodeArr[i].right = NodeArr[2 * i + 2];
  }
  return NodeArr[0];
}

function preShow(node) {
  if (node == null)
    return;
  console.log(node.val);
  preShow(node.left);
  preShow(node.right);
}

/**
 * @param {TreeNode} root
 * @return {number}
 */
var longestUnivaluePath = function (root) {
  root = createTree(root);
  if(root == null) return 0;
  let result = 0;

  function dfs(node) {
    if(node == null) return 0;
    let left = dfs(node.left), right = dfs(node.right);
    if(node.left && node.val == node.left.val) {
      left += 1;
    } else {
      left = 0;
    }
    if(node.right && node.val == node.right.val) {
      right += 1;
    } else {
      right = 0;
    }
    result = Math.max(result, left + right);
    // 只能选一边，不然两边都走的话，不符合题意
    return Math.max(left, right);
  }
  dfs(root);
  return result;
};
let root = [1,null,3,2,4,null,null,null,5];
// console.log(longestConsecutive(root));
// root = [2,null,3,2,null,1];
// console.log(longestConsecutive(root));
// root = [1, 2, 3];
// console.log(longestUnivaluePath(root));
// root = [2,1,3];
// console.log(longestUnivaluePath(root));
// root = [5,4,5,1,1,5];
// console.log(longestUnivaluePath(root));
// root = [1,4,5,4,4,5];
// console.log(longestUnivaluePath(root));
// root = [1,null,1,1,1,1,1,1];
// console.log(longestUnivaluePath(root));
root = [1,4,5,4,4,null,5];
console.log(longestUnivaluePath(root));

